
#include "CascHandler.h"
#include "log.h"

extern Log * pLog;

CascHandler::CascHandler()
{
}

int CascHandler::CascOpen(const TCHAR * szStorage)
{
	// Open the storage directory
	if (!CascOpenStorage(szStorage, 0, &hStorage))
	{
		assert(GetLastError() != ERROR_SUCCESS);
		nError = GetLastError();
	}

	return nError;
}

bool CascHandler::CascGetFile(const std::string &filename, BufferS_t *buffer) const
{
	//CASC_FIND_DATA FindData;
	//HANDLE hFind;
	HANDLE phFile;
	DWORD dwFlags;
	DWORD dwLocale;
	bool bFileFound = true;
	DWORD dwFileSizeHigh;
	DWORD dwBytesRead;

	// convert filename to lower case string
	std::string fn_lc(filename);
	std::transform(fn_lc.begin(), fn_lc.end(), fn_lc.begin(), ::tolower);
	
	dwFlags = 0;
	dwLocale = 0;

	if (!CascOpenFile(hStorage, filename.c_str(), dwLocale, dwFlags, &phFile))
	{
		pLog->Write("Could not open %s\n", filename.c_str());
		return false;
	}

	DWORD filesize = CascGetFileSize(phFile, &dwFileSizeHigh);

	// resize buffer and load file into that buffer
	buffer->resize(filesize);
	uint8_t *buf_p = (uint8_t*)&(*buffer)[0];

	LPOVERLAPPED lp = NULL;

	bool result = CascReadFile(phFile, buf_p, filesize, &dwBytesRead);

	if (filesize != dwBytesRead)
		result = false;

	CascCloseFile(phFile);

	return result;
}

bool CascHandler::CascClose()
{
	// Close storage and return
	if (hStorage != NULL)
		return CascCloseStorage(hStorage);

	return false;
}

